<script setup lang="ts">
import type { Recordable } from '@vben/types';

import { ref, computed } from 'vue';

import { Page, useVbenDrawer, type VbenFormProps } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';

import { Modal, Popconfirm, Space, Tabs } from 'ant-design-vue';
const { TabPane } = Tabs;
import dayjs from 'dayjs';

import {   
  useVbenVxeGrid,
  vxeCheckboxChecked,
  type VxeGridProps 
} from '#/adapter/vxe-table';

import {
  orderExport,
  orderList,
  orderRemove,
} from '#/api/trade/order';
import type { OrderForm } from '#/api/trade/order/model';
import { commonDownloadExcel } from '#/utils/file/download';

import orderDrawer from './order-drawer.vue';
import purchaseContractDrawer from '../purchaseContract/purchaseContract-drawer.vue';
import carCostDrawer from '../carCost/carCost-drawer.vue';
import refundTaxSettleDrawer from '../refundTaxSettle/refundTaxSettle-drawer.vue';
import { columns, querySchema, getColumns } from './data';

// 订单状态定义
const  ORDER_STATUS = {
  WAITING_PURCHASE: 'waiting_purchase', // 待采购
  PURCHASED: 'purchased', // 已采购
  SHIPPED: 'shipped', // 已发货
  INVALID: 'invalid', // 已作废
};

// 状态标签页配置
const statusTabs = [
  { key: 'all', label: '全部' },
  { key: ORDER_STATUS.WAITING_PURCHASE, label: '待采购' },
  { key: ORDER_STATUS.PURCHASED, label: '已采购' },
  { key: ORDER_STATUS.SHIPPED, label: '已发货' },
  { key: ORDER_STATUS.INVALID, label: '已作废' },
];

// 当前激活的状态tab
const activeStatus = ref('all');

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  // 处理区间选择器RangePicker时间格式 将一个字段映射为两个字段 搜索/导出会用到
  // 不需要直接删除
  // fieldMappingTime: [
  //  [
  //    'createTime',
  //    ['params[beginTime]', 'params[endTime]'],
  //    ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
  //  ],
  // ],
};

// 为每个状态创建独立的表格配置
const createGridOptions = (status: string): VxeGridProps => ({
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  // 根据状态动态生成列配置
  columns: getColumns(status),
  // height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const params: any = {
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        };
        // 只有当status不是'all'时才添加status参数
        if (status !== 'all') {
          params.status = status;
        }
        return await orderList(params);
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到，每个状态tab使用不同的ID
  id: `trade-order-${status}`
});

// 为每个状态创建独立的表格实例
const tableInstances = ref<Record<string, any>>({});

// 初始化所有状态的表格实例
statusTabs.forEach(tab => {
  const [BasicTable, tableApi] = useVbenVxeGrid({
    formOptions,
    gridOptions: createGridOptions(tab.key),
  });
  tableInstances.value[tab.key] = { BasicTable, tableApi };
});

// 获取当前激活状态的表格实例
const currentTableInstance = computed(() => {
  return tableInstances.value[activeStatus.value];
});

// 状态切换处理函数
function handleStatusChange(status: string) {
  activeStatus.value = status;
  tableInstances.value[status].tableApi.query();
}

const [OrderDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: orderDrawer,
});

const [PurchaseContractDrawer, purchaseContractDrawerApi] = useVbenDrawer({
  connectedComponent: purchaseContractDrawer,
});

const [CarCostDrawer, carCostDrawerApi] = useVbenDrawer({
  connectedComponent: carCostDrawer,
});

const [RefundTaxSettleDrawer, refundTaxSettleDrawerApi] = useVbenDrawer({
  connectedComponent: refundTaxSettleDrawer,
});

function handleAdd() {
  // 添加新订单时，如果不是"全部"tab页，自动设置当前tab页对应的状态
  const data: any = {};
  if (activeStatus.value !== 'all') {
    data.status = activeStatus.value;
  }
  drawerApi.setData(data);
  drawerApi.open();
}

async function handleEdit(row: Required<OrderForm>) {
  drawerApi.setData({ id: row.id });
  drawerApi.open();
}

async function handleDelete(row: Required<OrderForm>) {
  await orderRemove(row.id);
  await currentTableInstance.value.tableApi.query();
}

function handleMultiDelete() {
  const { tableApi } = currentTableInstance.value;
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: Required<OrderForm>) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await orderRemove(ids);
      await tableApi.query();
    },
  });
}

function handleDownloadExcel() {
  const { tableApi } = currentTableInstance.value;
  commonDownloadExcel(orderExport, '订单管理数据', tableApi.formApi.form.values, {
    fieldMappingTime: formOptions.fieldMappingTime,
  });
}

// 生成采购合同
function handlePurchaseContract() {
  const { tableApi } = currentTableInstance.value;
  const selectedRows = tableApi.grid.getCheckboxRecords();
  
  if (selectedRows.length === 0) {
    Modal.warning({
      title: '提示',
      content: '请选择要生成采购合同的订单',
    });
    return;
  }
  
  // 检查选中的订单是否符合生成采购合同的条件
  // 相同品牌，相同客户且未生成采购合同的订单可以一起生成采购合同
  const validOrders = selectedRows.filter(order => {
    // 检查是否已经有采购合同
    return !order.purchaseContractNo && order.status === ORDER_STATUS.WAITING_PURCHASE;
  });
  
  if (validOrders.length === 0) {
    Modal.warning({
      title: '提示',
      content: '选中的订单中没有符合条件的订单。只有状态为"待采购"且未生成采购合同的订单才能生成采购合同。',
    });
    return;
  }
  
  // 按品牌和客户分组检查
  const groupedOrders = new Map();
  validOrders.forEach(order => {
    const key = `${order.brandName}_${order.customerName}`;
    if (!groupedOrders.has(key)) {
      groupedOrders.set(key, []);
    }
    groupedOrders.get(key).push(order);
  });
  
  if (groupedOrders.size > 1) {
    Modal.warning({
      title: '提示',
      content: '选中的订单包含不同品牌或不同客户的订单，无法一起生成采购合同。请选择相同品牌和相同客户的订单。',
    });
    return;
  }
  
  // 获取第一个订单的信息用于预填充采购合同
  const firstOrder = validOrders[0];
  const contractData = {
    // 可以根据需要添加更多预填充字段
    orderIds: validOrders.map(order => order.id), // 传递关联的订单ID
  };
  
  purchaseContractDrawerApi.setData(contractData);
  purchaseContractDrawerApi.open();
}

// 车辆费用处理函数
function handleCarCost() {

  const { tableApi } = currentTableInstance.value;
  const selectedRows = tableApi.grid.getCheckboxRecords();
  
  if (selectedRows.length != 1) {
    Modal.warning({
      title: '提示',
      content: '请选择1个订单',
    });
    return;
  }

  const orderData = {
    orderId: selectedRows[0].id // 传递关联的订单ID
  }

  carCostDrawerApi.setData(orderData);
  carCostDrawerApi.open();
}

// 退税结算处理函数
function handleRefundTax() {
  const { tableApi } = currentTableInstance.value;
  const selectedRows = tableApi.grid.getCheckboxRecords();
  if (selectedRows.length !== 1) {
    Modal.warning({
      title: '提示',
      content: '请选择1个订单',
    });
    return;
  }
    //订单的状态必须为已采购
    if (selectedRows[0].status != ORDER_STATUS.SHIPPED) {
    Modal.warning({
      title: '提示',
      content: '请选择已发货的订单',
    });
    return;
  }
  const orderData = {
    orderId: selectedRows[0].id // 传递关联的订单ID
  }

  refundTaxSettleDrawerApi.setData(orderData);
  refundTaxSettleDrawerApi.open();
}
</script>

<template>
  <Page :auto-content-height="true">
    <Tabs 
      v-model:activeKey="activeStatus" 
      @change="handleStatusChange"
      class="mb-4"
    >
      <TabPane 
        v-for="tab in statusTabs" 
        :key="tab.key" 
        :tab="tab.label"
      >
        <component 
          :is="tableInstances[tab.key].BasicTable" 
        >
          <template #toolbar-actions>
            <Space>
              <!-- 生成采购合同 -->
              <a-button
               type="primary"
                v-access:code="['trade:order:purchase']"
                :disabled="!vxeCheckboxChecked(currentTableInstance.tableApi)"
                @click="handlePurchaseContract"
              >
                {{ $t('pages.common.purchase') }}
              </a-button>
              <!-- 车辆费用 -->
              <a-button
                type="primary"
                v-access:code="['trade:order:carCost']"
                @click="handleCarCost"
              >
                {{ $t('pages.common.carCost') }}
              </a-button>
               <!-- 退税结算 -->
               <a-button
                type="primary"
                v-access:code="['trade:refundTaxSettle:add']"
                @click="handleRefundTax"
              >
                {{ $t('pages.common.refundTax') }}
              </a-button>
               <!-- 不需要删除、新增按钮
              <a-button
                v-access:code="['trade:order:export']"
                @click="handleDownloadExcel"
              >
                {{ $t('pages.common.export') }}
              </a-button>
              
              <a-button
                :disabled="!vxeCheckboxChecked(currentTableInstance.tableApi)"
                danger
                type="primary" 
                v-access:code="['trade:order:remove']" 
                @click="handleMultiDelete">
                {{ $t('pages.common.delete') }}
              </a-button>
               
              <a-button
                type="primary"
                v-access:code="['trade:order:add']"
                @click="handleAdd"
              >
                {{ $t('pages.common.add') }}
              </a-button>
               -->
              <div>相同同品牌，相同客户且未生成采购合同的订单可以一起生成采购合同。</div>
            </Space>
          </template>
          <template #orderNo="{ row }">
            <a-button 
              type="link" 
              @click="handleEdit(row)"
              class="p-0 h-auto"
            >
              {{ row.orderNo }}
            </a-button>
          </template>
          <template #action="{ row }">
            <Space>
              <ghost-button
                v-access:code="['trade:order:edit']"
                @click.stop="handleEdit(row)"
              >
                {{ $t('pages.common.edit') }}
              </ghost-button>
              <Popconfirm
                :get-popup-container="getVxePopupContainer"
                placement="left"
                title="确认删除？"
                @confirm="handleDelete(row)"
              >
                <ghost-button
                  danger
                  v-access:code="['trade:order:remove']"
                  @click.stop=""
                >
                  {{ $t('pages.common.delete') }}
                </ghost-button>
              </Popconfirm>
            </Space>
          </template>
        </component>
      </TabPane>
    </Tabs>
    <OrderDrawer @reload="currentTableInstance.tableApi.query()" />
    <PurchaseContractDrawer @reload="currentTableInstance.tableApi.query()" />
    <CarCostDrawer @reload="currentTableInstance.tableApi.query()" />
    <RefundTaxSettleDrawer @reload="currentTableInstance.tableApi.query()" />
  </Page>
</template>
